#pragma once

#include "util.h"
#include "context.h"


template<typename T, class=typename std::enable_if<std::is_base_of<google::protobuf::Message, T>::value>::type >
inline void httpServerBack(std::uint32_t request_id, T* msg)
{
    int status_code = 404;
    std::string body;
    if (msg != nullptr)
    {
        if (!CTools::ToJson(body, *msg))
        {
            log_error("req to json failed, req:%s", msg->ShortDebugString().c_str());
        }
        else
        {
            log_debug("req:%s", msg->ShortDebugString().c_str());
            
            status_code = 200;
        }
    }
    std::map<std::string,std::string> heads;
    heads["Content-Type"] = "application/json";
    Ctx.msg_router.httpServerBack(request_id, status_code, heads, body);
}

template<typename T, class=typename std::enable_if<std::is_base_of<google::protobuf::Message, T>::value>::type >
inline std::uint32_t httpGet(const std::string& url, T* msg)
{
    std::string json_string;
    if (msg != nullptr)
    {
        if (!CTools::ToJson(json_string, *msg))
        {
            log_error("req to json failed, req:%s", msg->ShortDebugString().c_str());
            return 0;
        }
    }

    std::map<std::string,std::string> heads;
    heads["Content-Type"] = "application/json";

    std::uint32_t callback_id = 0;
    if (!Ctx.msg_router.sendHttpGET(url, json_string, heads, callback_id) || (callback_id == 0))
    {
        log_error("sendHttpGET failed, url:%s, callback_id:%u", url.c_str(), callback_id);
        return 0;
    }
    return callback_id;
}

template<typename T, class=typename std::enable_if<std::is_base_of<google::protobuf::Message, T>::value>::type >
inline std::uint32_t httpPost(const std::string& url, T* msg)
{
    std::string json_string;
    if (msg != nullptr)
    {
        if (!CTools::ToJson(json_string, *msg))
        {
            log_error("req to json failed, req:%s", msg->ShortDebugString().c_str());
            return 0;
        }
    }

    std::map<std::string,std::string> heads;
    heads["Content-Type"] = "application/json";

    std::uint32_t callback_id = 0;
    if (!Ctx.msg_router.sendHttpPOST(url, json_string, heads, callback_id) || (callback_id == 0))
    {
        log_error("sendHttpPOST failed, url:%s, callback_id:%u", url.c_str(), callback_id);
        return 0;
    }
    return callback_id;
}









